
package com.rt.schedulenew.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rt.schedulebase.dto.*;
import com.rt.schedulebase.entity.*;
import com.rt.schedulebase.mapper.ExamApplyItemMapper;
import com.rt.schedulebase.mapper.ExamApplyMapper;
import com.rt.schedulebase.mapper.ExamScheduleMapper;
import com.rt.schedulenew.api.*;
import com.rt.schedulenew.utils.base.CommonUtil;
import com.rt.schedulenew.utils.base.ConstantsUtil;
import com.rt.schedulenew.utils.global.JsonResult;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import com.rt.schedulenew.utils.pkgenerator.PKGeneratorSingle;
import com.rt.schedulenew.utils.util.DateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class ScheduleSignServiceImpl extends ServiceImpl<ExamApplyMapper, ExamApply> implements IScheduleSignService {

    private static final Logger log = LoggerFactory.getLogger(ScheduleSignServiceImpl.class);

    @Autowired
    private ExamApplyItemMapper examApplyItemMapper;
    @Autowired
    private IExamScheduleService examScheduleService;
    @Autowired
    private IExamScheduleItemService examScheduleItemService;
    @Autowired
    private ICommonService commonServiceImpl;
    @Autowired
    private IConfigService configServiceImpl;
    @Autowired
    private ExamScheduleMapper examScheduleMapper;
    @Autowired
    private IDictTerminalService dictTerminalService;
    @Autowired
    private IDictHospitalService dictHospitalService;

    /**
     * 预约退回
     *
     * @param dto 申请单
     * @return 返回结果
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public JsonResult gotBack(ExamApplyDto dto) {
        if (StringUtils.isBlank(dto.getApplyNo())) {
            return JsonResultUtil.failure("失败");
        }
        String applyNo = dto.getApplyNo().split(",")[0];
        dto.setApplyNo(applyNo);

        Map<String, Object> map = new HashMap<>();
        map.put("applyNo", applyNo);
        map.put("terminalType", "");
        ExamApplyDto ea = baseMapper.getExamApply(map);

        if (ea == null) {
            String strReturn = "没有您的检查申请信息,如有疑问请到护士站咨询";
            String reminder = configServiceImpl.customReminder(ConstantsUtil.ConfigName.NO_QUERY_EXAM_APPLY_REMINDER.getKey(), "", "");
            if (StringUtils.isNotBlank(reminder)) {
                strReturn = reminder;
            }
            return JsonResultUtil.failure(strReturn);
        }
        List<ExamApplyItemDto> items = commonServiceImpl.getExamApplyItem(dto.getMergeNo(), ea);
        if (items.size() == 0) {
            return JsonResultUtil.failure("您的检查项目单不存在，如有疑问请到护士站咨询！");
        }
        commonServiceImpl.getScheduleToExamApply(dto, ea);
        boolean isExamClass4Organ = configServiceImpl.getOrganExamClassList().contains(ea.getExamClass());
        double reqCount = 1.0;
        if (isExamClass4Organ) {
            reqCount = commonServiceImpl.getReqOrganByItems(items);
        }
        if (StringUtils.isNotBlank(ea.getScheduledId())) {
            ExamApplyDto eaDto = new ExamApplyDto();
            eaDto.setOrgans(ea.getOrgans());
            eaDto.setApplyNo(ea.getApplyNo());
            eaDto.setScheduledId(ea.getScheduledId());
            eaDto.setScheduleDate(ea.getScheduleDate());
            eaDto.setNextApmRatio(ea.getNextApmRatio());
            eaDto.setMergeNo(dto.getMergeNo());
            eaDto.setReqCount(reqCount);
            eaDto.setRegularIdList(ea.getRegularIdList());
            eaDto.setApmCode(ea.getApmCode());
            eaDto.setExamClass(ea.getExamClass());
            if ("08".equals(ea.getScheduleStatus())) {
                eaDto.setExamClass(ea.getExamClass());
                eaDto.setTerminalType(dto.getTerminalType());
            }
            // 取消预约信息
            commonServiceImpl.cancelScheduleInfo(eaDto, isExamClass4Organ);
        }
        // 生成id
        String scheduledId = PKGeneratorSingle.getInstance().nextPKStr();
        ExamSchedule es = new ExamSchedule();
        es.setScheduledId(scheduledId);
        es.setScheduleStatus("04");
        examScheduleService.insertSelective(es);
        List<String> mergeNos = CommonUtil.split2List(dto.getMergeNo());
        for (String mergeNo : mergeNos) {
            int idx = mergeNo.lastIndexOf("-");
            String applyNoStr = mergeNo.substring(0, idx);
            String itemNo = mergeNo.substring(idx + 1);
            ExamScheduleItem esi = new ExamScheduleItem();
            esi.setScheduledId(scheduledId);
            esi.setApplyNo(applyNoStr);
            esi.setItemNo(Long.parseLong(itemNo));
            examScheduleItemService.insertSelective(esi);
        }
        return JsonResultUtil.success();
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public JsonResult cancelExamApply(ExamApplyDto dto) {
        if (StringUtils.isBlank(dto.getMergeNo()) && StringUtils.isBlank(dto.getApplyNo())) {
            return JsonResultUtil.failure("作废申请单失败，单号不能为空！");
        }
        List<String> applyNoList = new ArrayList<>();
        List<String> applyNoStr = new ArrayList<>();
        List<String> itemNameStr = new ArrayList<>();
        if (StringUtils.isNotBlank(dto.getMergeNo())) {
            String[] mergeNosArr = dto.getMergeNo().split(",");
            Set<String> set = new HashSet<>();
            Collections.addAll(set, mergeNosArr);
            for (String mergeNo : set) {
                int idx = mergeNo.lastIndexOf("-");
                String applyno = mergeNo.substring(0, idx);
                String itemNo = mergeNo.substring(idx + 1);
                ExamApplyDto ea = new ExamApplyDto();
                ea.setApplyNo(applyno);
                ea.setItemNo(Long.parseLong(itemNo));
                List<ExamApplyDto> esList = baseMapper.getExamScheduleForItem(ea);
                if (esList != null && esList.size() > 0) {
                    for (ExamApplyDto examApply : esList) {
                        if (StringUtils.isBlank(examApply.getApplyNo())) {
                            if (!applyNoList.contains(applyno)) {
                                applyNoList.add(applyno);
                            }
                            ExamApplyItem m = new ExamApplyItem();
                            m.setExamStatus("00");
                            UpdateWrapper<ExamApplyItem> update = new UpdateWrapper<>();
                            update.eq("APPLY_NO", applyno);
                            update.eq("ITEM_NO", itemNo);
                            examApplyItemMapper.update(m, update);
                            List<ExamApplyItemDto> items = new ArrayList<>();
                            ExamApplyItemDto item = new ExamApplyItemDto();
                            item.setApplyNo(applyno);
                            item.setItemNo(Long.parseLong(itemNo));
                            item.setItemName(examApply.getItemNameStr());
                            items.add(item);
                            examApply.setApplyNo(applyno);
                            examApply.setItems(items);
                            examApply.setTerminalType(dto.getTerminalType());
                            examApply.setActType(ConstantsUtil.ActType.DEL_ITEM.getType());
                            commonServiceImpl.addExamScheduleAct(examApply, commonServiceImpl.dictUsers(dto));
                        } else {
                            if (!applyNoStr.contains(applyno)) {
                                applyNoStr.add(applyno);
                            }
                            itemNameStr.add(examApply.getItemNameStr());
                        }
                    }
                }
            }
        } else {
            ExamApplyDto ea2 = new ExamApplyDto();
            ea2.setApplyNo(dto.getApplyNo());
            List<ExamApplyDto> esList2 = baseMapper.getExamScheduleForItem(ea2);
            if (esList2 != null && esList2.size() > 0) {
                for (ExamApplyDto examApply2 : esList2) {
                    if (StringUtils.isBlank(examApply2.getApplyNo())) {
                        if (!applyNoList.contains(dto.getApplyNo())) {
                            applyNoList.add(dto.getApplyNo());
                        }
                        ExamApplyItem j = new ExamApplyItem();
                        j.setExamStatus("00");
                        UpdateWrapper<ExamApplyItem> update2 = new UpdateWrapper<>();
                        update2.eq("APPLY_NO", dto.getApplyNo());
                        update2.eq("ITEM_NO", examApply2.getItemNo());
                        examApplyItemMapper.update(j, update2);
                        List<ExamApplyItemDto> items2 = new ArrayList<>();
                        ExamApplyItemDto item2 = new ExamApplyItemDto();
                        item2.setApplyNo(dto.getApplyNo());
                        item2.setItemNo(examApply2.getItemNo());
                        item2.setItemName(examApply2.getItemNameStr());

                        items2.add(item2);
                        examApply2.setApplyNo(dto.getApplyNo());
                        examApply2.setItems(items2);
                        examApply2.setTerminalType(dto.getTerminalType());
                        examApply2.setActType(ConstantsUtil.ActType.DEL_ITEM.getType());
                        commonServiceImpl.addExamScheduleAct(examApply2, commonServiceImpl.dictUsers(dto));
                    }
                }
            }
        }
        if (CollectionUtils.isNotEmpty(applyNoList)) {
            for (String applyNo : applyNoList) {
                QueryWrapper<ExamApplyItem> items3 = new QueryWrapper<>();
                items3.eq("APPLY_NO", applyNo);
                items3.isNull("EXAM_STATUS");
                int count = examApplyItemMapper.selectCount(items3);
                if (count == 0) {
                    ExamApply k = new ExamApply();
                    k.setApplyStatus("00");
                    UpdateWrapper<ExamApply> update3 = new UpdateWrapper<>();
                    update3.eq("APPLY_NO", applyNo);
                    baseMapper.update(k, update3);
                    QueryWrapper<ExamApply> eaQuery = new QueryWrapper<>();
                    eaQuery.eq("APPLY_NO", applyNo);
                    eaQuery.eq("APPLY_STATUS", "00");
                    List<ExamApply> list = baseMapper.selectList(eaQuery);
                    if (CollectionUtils.isEmpty(list)) {
                        continue;
                    }
                    ExamApplyDto examApply3 = new ExamApplyDto();
                    List<ExamApplyItemDto> item3 = new ArrayList<>();
                    examApply3.setItems(item3);
                    examApply3.setApplyNo(applyNo);
                    examApply3.setTerminalType(dto.getTerminalType());
                    examApply3.setActType(ConstantsUtil.ActType.DEL_APPLY.getType());
                    examApply3.setName(list.get(0).getName());
                    examApply3.setAge(list.get(0).getAge());
                    examApply3.setSex(list.get(0).getSex());
                    examApply3.setSickId(list.get(0).getSickId());
                    examApply3.setHospitalCode(list.get(0).getHospitalCode());
                    commonServiceImpl.addExamScheduleAct(examApply3, commonServiceImpl.dictUsers(dto));
                }
            }
        }
        if (CollectionUtils.isNotEmpty(applyNoStr)) {
            return JsonResultUtil.failure("申请单：" + applyNoStr + " 中存在已报到项目：" + itemNameStr + "无法作废！");
        }
        return JsonResultUtil.success();
    }

    @Override
    public JsonResult getDateFirst(ExamApplyDto dto) {
        ExamApplyDto ea = new ExamApplyDto();
        String isCompliance = commonServiceImpl.mergeRuleForScheduleJudge(ea, dto);
        if (StringUtils.isNotBlank(isCompliance)) {
            return JsonResultUtil.failure(isCompliance);
        }
        dto.setPerformDept(ea.getPerformDept());
        dto.setExamClass(ea.getExamClass());
        List<DictExamQueueDto> lsQueue = commonServiceImpl.getQueueList(dto);
        if (CollectionUtils.isEmpty(lsQueue)) {
            String queueNameStr = (dto.getQueueName() != null) ? dto.getQueueName() : "";
            String strReturn = "由于系统未设置" + ea.getExamClass() + "检查类别" + queueNameStr + "的可预约队列，您的检查申请暂时不能预约，如有疑问请到护士站咨询！";
            String reminder = configServiceImpl.customReminder(ConstantsUtil.ConfigName.NO_QUERY_EXAM_APPLY_REMINDER.getKey(), "", ea.getExamClass());
            if (StringUtils.isNotBlank(reminder)) {
                strReturn = reminder;
            }
            return JsonResultUtil.failure(strReturn);
        }
        String isSchedule = commonServiceImpl.isScheduleByFlags(ea.getItems(), dto.getTerminalType(), ea.getChargeType());
        if (StringUtils.isNotBlank(isSchedule)) {
            return JsonResultUtil.failure(isSchedule);
        }
        boolean isGestational = false;
        if (ea.getSex() != null && ea.getSex().contains(ConstantsUtil.Gender.WOMAN.getValue())) {
            List<ExamApplyItemDto> gestationalItems = commonServiceImpl.getGestationalItems(ea.getItems());
            if (CollectionUtils.isNotEmpty(gestationalItems)) {
                isGestational = true;
                if (StringUtils.isBlank(ea.getLastMensesDate())) {
                    ea.setLastMensesDate(commonServiceImpl.getLastMensesDate(ea.getSickId()));
                    if (StringUtils.isBlank(ea.getLastMensesDate())) {
                        return JsonResultUtil.failure("该检查申请需要填写末次月经日期");
                    }
                }
            }
        }
        Map<String, String> queueDateMap = commonServiceImpl.getBeginDateAndExpireDate(ea.getApplyNo(), ea.getHospitalCode(), ea.getPatientSource(), ea.getBeginDays());
        String startDate = queueDateMap.get("beginDate");
        String expireDate = queueDateMap.get("expireDate");
        if (isGestational) {
            String startDate_gestational = commonServiceImpl.getStartDate(ea.getLastMensesDate(), ea.getItems());
            if (startDate_gestational.compareTo(startDate) > 0) {
                startDate = startDate_gestational;
            }
            String expireDate_gestational = commonServiceImpl.getExpireDate4Gestational(ea.getLastMensesDate(), ea.getItems());
            if (StringUtils.isNotBlank(expireDate_gestational)) {
                if (StringUtils.isNotBlank(expireDate)) {
                    if (expireDate.compareTo(expireDate_gestational) > 0) {
                        expireDate = expireDate_gestational;
                    }
                } else {
                    expireDate = expireDate_gestational;
                }
            }
        }
        String currDate = DateUtil.getCurrDateStr();
        if (StringUtils.isNotBlank(startDate)) {
            currDate = startDate;
        }
        String endDate = DateUtil.addDays2(currDate, 35);
        if (StringUtils.isNotBlank(expireDate)) {
            endDate = expireDate;
        }
        commonServiceImpl.getOrgansOrPower(ea);
        ea.setStaffName(dto.getStaffName());
        // 查询日期时段内每一天是否有可以预约的时段，有就直接返回
        while (currDate.compareTo(endDate) < 0) {
            ExamApplyDto examApplyDto = commonServiceImpl.getScheduleDate(lsQueue, currDate, ea);
            if (examApplyDto != null && "1".equals(examApplyDto.getEnabled())) {
                Map<String, String> map = new HashMap<>();
                map.put("scheduleDate", currDate);
                map.put("scheduleApm", examApplyDto.getScheduleApm());
                return JsonResultUtil.success(map);
            }
            currDate = DateUtil.addDays2(currDate, 1);
        }
        return JsonResultUtil.failure("系统未找到合适的预约时间");
    }

    @Override
    public JsonResult getEnabledSignClasses(DictExamClassDto dto, String terminalType) {
        if (!ConstantsUtil.TerminalType.SELF.getType().equals(dto.getTerminalType())) {
            return null;
        }
        DictTerminalDto dictTerminalDto = new DictTerminalDto();
        dictTerminalDto.setIpAddress(dto.getIpAddress());
        DictTerminalDto terminalDto = dictTerminalService.getSelfDeviceInfo(dictTerminalDto);
        if (terminalDto == null || StringUtils.isBlank(terminalDto.getSignExamClass())) {
            return JsonResultUtil.failure("本机未配置可报到的检查类别，如有疑问请到护士站咨询！");
        }
        List<String> sickIds = new ArrayList<String>();
        if (StringUtils.isBlank(dto.getSickId())) {
            ExamApplyDto ea = new ExamApplyDto();
            ea.setIcCard(dto.getIcCard());
            String icCard = ea.getIcCard();
            ea.setCommonCard(icCard);
            ea.setIcCard(null);
            if (StringUtils.isNotBlank(terminalDto.getIcCardInputSupportType())) {
                String icCardInputSupportType = terminalDto.getIcCardInputSupportType();
                if ("common_card".equals(icCardInputSupportType)) {
                    ea.setCommonCard(icCard);
                } else if ("sick_id".equals(icCardInputSupportType)) {
                    ea.setSickId(icCard);
                    ea.setCommonCard(null);
                } else if ("ic_card".equals(icCardInputSupportType)) {
                    ea.setIcCard(icCard);
                    ea.setCommonCard(null);
                } else if ("inpatient_no".equals(icCardInputSupportType)) {
                    ea.setInpatientNo(icCard);
                } else if ("outpatient_no".equals(icCardInputSupportType)) {
                    ea.setOutpatientNo(icCard);
                } else if ("apply_no".equals(icCardInputSupportType)) {
                    ea.setApplyNo(icCard);
                } else if ("identity_card".equals(icCardInputSupportType)) {
                    ea.setIdentityCard(icCard);
                } else if ("mi_card".equals(icCardInputSupportType)) {
                    ea.setMiCard(icCard);
                }
            }
            sickIds = commonServiceImpl.getSickIds(ea);
        } else {
            sickIds.add(dto.getSickId());
        }
        if (sickIds.size() == 0) {
            return JsonResultUtil.failure("没有您的检查申请记录，如有疑问请到护士站咨询！");
        }
        ExamApplyDto examApplyDto = new ExamApplyDto();
        examApplyDto.setSickIds(sickIds);
        String date = DateUtil.getCurrDateStr();
        examApplyDto.setScheduleDate(date);
        examApplyDto.setScheduleStatus("08");
        examApplyDto.setScheduleHospital(terminalDto.getHospitalCode());
        examApplyDto.setExamClasses(CommonUtil.split2List(terminalDto.getSignExamClass()));
        List<ExamApplyDto> lsExamApplyDto = baseMapper.getExamApplyList(examApplyDto);
        if (lsExamApplyDto.size() == 0) {
            date = DateUtil.addDays(1);
            examApplyDto.setScheduleDate(date);
            examApplyDto.setTimeStart("03:00");
            lsExamApplyDto = baseMapper.getExamApplyList(examApplyDto);
            examApplyDto.setScheduleDate(DateUtil.getCurrDateStr());
            examApplyDto.setTimeStart(null);
        }
        if (lsExamApplyDto.size() > 0) {
            List<String> examClassList = CommonUtil.split2List(terminalDto.getSignExamClass());
            examApplyDto.setExamClasses(examClassList);
            lsExamApplyDto = baseMapper.getExamApplyList(examApplyDto);
            if (lsExamApplyDto.size() == 0) {
                String strReturn = "本机仅提供" + terminalDto.getSignExamClass() + "检查报到，如有疑问请到护士站咨询！";
                String reminder = configServiceImpl.customReminder(ConstantsUtil.ConfigName.NO_SIGN_QUEUE_BY_SELF_REMINDER.getKey(), "", terminalDto.getSignExamClass());
                if (StringUtils.isNotBlank(reminder)) {
                    strReturn = reminder;
                }
                return JsonResultUtil.failure(strReturn);
            }
            List<String> list = new ArrayList<>();
            for (ExamApplyDto ead : lsExamApplyDto) {
                if (!list.contains(ead.getExamClass())) {
                    list.add(ead.getExamClass());
                }
            }
            return JsonResultUtil.success("成功", list);
        } else {
            examApplyDto.setScheduleDate(null);
            examApplyDto.setScheduleHospital(null);
            examApplyDto.setStartDate(DateUtil.getCurrDateStr());
            lsExamApplyDto = baseMapper.getExamApplyList(examApplyDto);
            if (lsExamApplyDto == null || lsExamApplyDto.isEmpty()) {
                return JsonResultUtil.failure("没有您的" + terminalDto.getSignExamClass() + "检查申请记录，如有疑问请到护士站咨询！");
            }
            List<String> tmpList = new ArrayList<>();
            StringBuilder scheduleMsg = new StringBuilder();
            int resultCount = 1;
            for (ExamApplyDto examApply : lsExamApplyDto) {
                if (!tmpList.contains(examApply.getScheduledId())) {
                    StringBuilder itemNames = new StringBuilder();
                    ScheduleDetailDto scheduleDetailDto = new ScheduleDetailDto();
                    scheduleDetailDto.setScheduledId(examApply.getScheduledId());
                    List<ScheduleDetailDto> scheduleDetailList = examScheduleMapper.getScheduleDetailList(scheduleDetailDto);
                    if (scheduleDetailList != null && !scheduleDetailList.isEmpty()) {
                        StringBuilder mergeNos = new StringBuilder();
                        for (ScheduleDetailDto apply : scheduleDetailList) {
                            mergeNos.append("," + apply.getApplyNo() + "-" + apply.getItemNo());
                        }
                        examApply.setMergeNo(StringUtils.isNotBlank(mergeNos.toString()) ? mergeNos.substring(1) : "");
                        List<ExamApplyItemDto> eais = commonServiceImpl.getExamApplyItem(examApply.getMergeNo(), examApply);
                        if (eais != null && !eais.isEmpty()) {
                            for (ExamApplyItemDto itemDto : eais) {
                                itemNames.append("," + itemDto.getItemName());
                            }
                        }
                    }
                    String scheduleHospitalName = "";
                    if (StringUtils.isNotBlank(examApply.getScheduleHospital())) {
                        DictHospitalDto dictHospitalDto = new DictHospitalDto();
                        dictHospitalDto.setHospitalCode(examApply.getScheduleHospital());
                        List<DictHospital> hospitalList = dictHospitalService.selectList(dictHospitalDto);
                        if (hospitalList != null && !hospitalList.isEmpty()) {
                            scheduleHospitalName = hospitalList.get(0).getHospitalName();
                        }
                    }
                    String statusMsg = (StringUtils.isNotBlank(examApply.getExamStatus()) && Integer.parseInt(examApply.getExamStatus()) >= 10) ? "已报到" : "已预约";
                    if (StringUtils.isBlank(dto.getApplication())) {
                        scheduleMsg.append("（" + resultCount + "）[" + statusMsg + "]<br/>预约院区：" + scheduleHospitalName + "<br/>预约日期：" + examApply.getScheduleDate() + "<br/>预约时段：" + examApply.getScheduleApm() + "<br/>检查类别：" + examApply.getExamClass() + "<br/>检查项目：" + (StringUtils.isNotBlank(itemNames.toString()) ? itemNames.substring(1) : "") + "<br/>");
                    } else {
                        scheduleMsg.append("（" + resultCount + "）[" + statusMsg + "]预约院区：" + scheduleHospitalName + "，预约日期：" + examApply.getScheduleDate() + "，预约时段：" + examApply.getScheduleApm() + "，检查类别：" + examApply.getExamClass() + "，检查项目：" + (StringUtils.isNotBlank(itemNames.toString()) ? itemNames.substring(1) : "") + "。");
                    }
                    tmpList.add(examApply.getScheduledId());
                    ++resultCount;
                }
            }
            if (StringUtils.isBlank(terminalType)) {
                return JsonResultUtil.failure(scheduleMsg.toString());
            }
            return JsonResultUtil.failure(scheduleMsg.toString());
        }
    }

    /***
     * 预约冲突检查
     */
    @Override
    public JsonResult scheduleConflict(ExamApplyDto dto) {
        if (StringUtils.isNotBlank(dto.getMergeNo())) {
            List<String> applyNos = CommonUtil.mergeNo2ApplyNos(dto.getMergeNo());
            dto.setApplyNos(applyNos);
            dto.setApplyNo(applyNos.get(0));
        } else {
            List<String> applyNos = new ArrayList<>();
            applyNos.add(dto.getApplyNo());
            dto.setApplyNos(applyNos);
        }
        if (StringUtils.isBlank(dto.getSickId())) {
            ExamApplyDto ea = commonServiceImpl.getExamApplyInfo(dto.getApplyNo(), dto.getTerminalType());
            dto.setSickId(ea.getSickId());
            List<ExamApplyItemDto> item = commonServiceImpl.getExamApplyItem(dto.getMergeNo(), ea);
            dto.setItems(item);
        }
        String flag = configServiceImpl.getConfigByName(ConstantsUtil.ConfigName.IS_NOT_ALLOW_SCHEDULE_BY_CONFLICT.getKey());
        if (StringUtils.isBlank(flag) || "F".equals(dto.getTerminalType())) {
            flag = "1";
        }
        String startTime = dto.getStartTime();
        // String endTime = dto.getEndTime();
        if (StringUtils.isBlank(startTime) && StringUtils.isNotBlank(dto.getScheduleApm())) {
            String[] arr = dto.getScheduleApm().split("~");
            if (arr.length > 1) {
                dto.setStartTime(arr[0]);
                dto.setEndTime(arr[1]);
            }
        }
        // 预约冲突
        Map<String, Object> resultMap = configServiceImpl.hasOtherSchedule(dto);
        if (org.apache.commons.collections4.MapUtils.isNotEmpty(resultMap)) {
            resultMap.put("flag", flag);
            resultMap.put("desc", resultMap.get("examClass") + "，与项目名称:" + resultMap.get("itemName") + " " + resultMap.get("message"));
            return JsonResultUtil.failure("2", resultMap.get("title") + "", resultMap);
        }
        resultMap = configServiceImpl.noOneDayEnhanceOrClam(dto);
        if (org.apache.commons.collections4.MapUtils.isNotEmpty(resultMap)) {
            resultMap.put("flag", flag);
            resultMap.put("desc", resultMap.get("examClass") + "，与项目名称:" + resultMap.get("itemName") + " " + resultMap.get("message"));
            return JsonResultUtil.failure("2", resultMap.get("title") + "", resultMap);
        }
        resultMap = configServiceImpl.noOneDayItem(dto);
        if (org.apache.commons.collections4.MapUtils.isNotEmpty(resultMap)) {
            resultMap.put("flag", flag);
            resultMap.put("desc", resultMap.get("examClass") + "，与项目名称:" + resultMap.get("itemName") + " " + resultMap.get("message"));
            return JsonResultUtil.failure("2", resultMap.get("title") + "", resultMap);
        }
        ExamScheduleDto examSchedule = new ExamScheduleDto();
        examSchedule.setScheduledDate(dto.getScheduleDate());
        examSchedule.setScheduleApm(dto.getScheduleApm());
        examSchedule.setHospitalCode(dto.getHospitalCode());
        examSchedule.setExamClass(dto.getExamClass());
        examSchedule.setPerformDept(dto.getPerformDept());
        examSchedule.setTimeStart(dto.getStartTime());
        String desc = configServiceImpl.isItemBefore(dto, examSchedule);
        if (StringUtils.isNotBlank(desc)) {
            resultMap = new HashMap<>();
            resultMap.put("desc", desc);
            resultMap.put("flag", flag);
            return JsonResultUtil.failure("2", "A列表项目比B列表项目至少优先或延后多少天", resultMap);
        }
        return JsonResultUtil.success("成功");
    }
}
